<template>
  <div id="app">
    <nav class="main-nav">
      <div class="nav-left">
        <router-link to="/" class="logo">BlogHub</router-link>
      </div>
      <div class="nav-right">
        <router-link to="/">首页</router-link>
        <router-link to="/editor">写文章</router-link>
        <router-link to="/profile">个人中心</router-link>
        <template v-if="userInfo">
          <span class="user-info">
            <img :src="userInfo.avatarUrl || defaultAvatar" class="nav-avatar" />
            {{ userInfo.username }}
            <a href="#" @click.prevent="logout" class="logout-link">退出</a>
          </span>
        </template>
        <template v-else>
          <router-link to="/login">登录/注册</router-link>
        </template>
      </div>
    </nav>
    <main>
      <router-view/>
    </main>
  </div>
</template>

<script>
import UserStorage from '@/utils/userStorage'
export default {
  data() {
    return {
      userInfo: null,
      defaultAvatar: ''
    }
  },
  created() {
    this.refreshUser()
  },
  methods: {
    refreshUser() {
      this.userInfo = UserStorage.getUserInfo()
    },
    logout() {
      UserStorage.clearUserInfo()
      this.refreshUser()
      this.$router.push('/login')
    }
  },
  watch: {
    // 监听路由变化，切换页面时刷新用户信息
    $route() {
      this.refreshUser()
    }
  }
}
</script>

<style>
:root {
  --primary: #42b983;
  --bg: #f7f8fa;
  --card: #fff;
  --border: #e0e0e0;
  --text: #2c3e50;
}
#app {
  font-family: 'Segoe UI', Avenir, Helvetica, Arial, sans-serif;
  background: var(--bg);
  min-height: 100vh;
  color: var(--text);
}
.main-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 40px;
  height: 64px;
  background: #fff;
  border-bottom: 1px solid var(--border);
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}
.logo {
  font-size: 1.5rem;
  font-weight: bold;
  color: var(--primary);
  text-decoration: none;
}
.nav-right a {
  margin-left: 24px;
  color: var(--text);
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s;
}
.nav-right a.router-link-exact-active {
  color: var(--primary);
}
.nav-right a:hover {
  color: #1890ff;
}
main {
  max-width: 900px;
  margin: 32px auto 0 auto;
  padding: 24px;
  background: var(--card);
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.04);
  min-height: 600px;
}
@media (max-width: 600px) {
  .main-nav { flex-direction: column; height: auto; padding: 0 10px; }
  .nav-right a { margin-left: 10px; }
  main { padding: 8px; }
}
.user-info {
  display: inline-flex;
  align-items: center;
  margin-left: 24px;
}
.nav-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  margin-right: 8px;
  border: 1.5px solid #42b983;
  background: #fff;
}
.logout-link {
  color: #ff4d4f;
  margin-left: 10px;
  cursor: pointer;
  font-size: 0.98rem;
}
.logout-link:hover {
  text-decoration: underline;
}
</style>
